package api;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/allread")
public class AllReadcountServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误";
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if(userInfo != null) {
            //登录状态
            int uid = userInfo.getUid();
            if (uid > 0) {
                //查询数据库得到文章列表
                //得到connection
                Connection connection = DBUtils.getConnection();
                //开始
                String sql = "select sum(readcount) as count from article where uid = ?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1, uid);
                ResultSet resultSet = statement.executeQuery();
                if (resultSet.next()) {
                    userInfo.setCount(resultSet.getInt("count"));
                }
                msg = "";
                //关闭资源
                DBUtils.close(resultSet, statement, null);
                DBUtils.close(resultSet, statement, connection);

                //结束
            }
            else {
                msg = "非法参数！";
            }
        }
        else {
            msg = "未登录";
        }

        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,userInfo,msg)));
    }
}
